/* eslint-disable no-param-reassign */
import { useControlController, useNamespace } from '@ibiz-template/vue3-util';
import { IDEEditForm } from '@ibiz/model-core';
import { defineComponent, PropType, reactive } from 'vue';
import { EditFormController } from './edit-form.controller';

export const EditFormControl = defineComponent({
  name: 'IBizEditFormControl',
  props: {
    modelData: {
      type: Object as PropType<IDEEditForm>,
      required: true,
    },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    isSimple: { type: Boolean, required: false },
    data: { type: Object as PropType<IData>, required: false },
  },
  setup(props) {
    const c = useControlController(
      (...args) => new EditFormController(...args),
    );

    if (props.isSimple) {
      // 简单模式下 默认不加载数据 isLoaded = true
      c.state.isLoaded = true;
    }

    const ns = useNamespace(`control-${c.model.controlType!.toLowerCase()}`);

    c.evt.on('onCreated', () => {
      // 表单成员state响应式
      const keys = Object.keys(c.details);
      keys.forEach(key => {
        const detail = c.details[key];
        detail.state = reactive(detail.state);
      });
    });

    return { c, ns };
  },

  render() {
    return (
      <iBizFormControl class={this.ns.b()} controller={this.c}>
        {{ ...this.$slots }}
      </iBizFormControl>
    );
  },
});
